<template>
  <div>
    <h2>登录</h2>
    <el-form @submit.native.prevent="login">
      <el-form-item label="账号">
        <el-input v-model="loginUsername" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="loginPassword" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">登录</el-button>
        <el-button type="info" @click="showRegisterDialog = true">注册</el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="showRegisterDialog" title="Register" @close="resetRegisterForm">
      <el-form @submit.native.prevent="register">
        <el-form-item label="账号">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="userForm.password" />
        </el-form-item>
        <el-form-item label="城市">
          <el-input  v-model="userForm.city" />
        </el-form-item>
        <el-form-item label="头像">
          <el-input  v-model="userForm.avatar" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-button @click="test">Test</el-button>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import { user } from '@/stores/counter.js'
import request from "@/axios/axiosUtils.js";
import {useRouter} from "vue-router";
const userStore = user()
let showRegisterDialog = ref(false);
const loginUsername = ref('')
const loginPassword = ref('')

const userForm=reactive({
  username:'test1',
  password:'123456',
  email:'2346883584@qq.com',
  city:'湛江',
  avatar:'sfag',
})
const router= useRouter()
const login =  () => {
  try {
    userStore.login(loginUsername.value, loginPassword.value).then((res)=>{

      userStore.getInfo().then((res)=>{
        console.log('Logged in successfully')
        console.log(res)
        router.push('/check');
      })
    })

  } catch (error) {
    console.error('Error logging in', error)
  }
}

const register = () => {
  try {
    userStore.register(userForm).then((res)=>{
      console.log('Registered successfully')
      showRegisterDialog.value = false
      resetRegisterForm()
    })

  } catch (error) {
    console.error('Error registering', error)
  }
}

const resetRegisterForm = () => {
  userForm.username = '';
  userForm.password = '';
  userForm.email = '';
  userForm.city = '';
  userForm.avatar = '';
}

const test = () => {
  request.get('/test').then((res)=>{
    console.log(res)
  })
}
</script>

<style scoped>
</style>